import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from './routes'

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  document.title = `${to.meta.title || 'vite-project'} `
  const userInfo = localStorage.getItem('userInfo')
  const permissInfo = localStorage.getItem('permiss')
  const role = permissInfo && JSON.parse(permissInfo).permissRole

  if (!userInfo && to.path !== '/login') {
    next('/login')
  } else if (to?.meta?.role && to.meta.role !== role) {
    // 如果没有权限，则进入403
    next('/403')
  } else {
    next()
  }
})

export default router
